package com.ifast.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.BaseController;
import com.ifast.common.domain.DictDO;
import com.ifast.common.domain.Tree;
import com.ifast.common.service.DictService;
import com.ifast.common.utils.Result;
import com.ifast.sys.dao.UserRoleDao;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.domain.RoleDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.domain.UserRoleDO;
import com.ifast.sys.service.RoleService;
import com.ifast.sys.service.UserService;
import com.ifast.sys.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * <pre>
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private String prefix = "sys/user";
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    DictService dictService;
    @Resource
    UserRoleDao userRoleDao;
    
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }
    
    @GetMapping("/list")
    @ResponseBody
    Result<Page<UserDO>> list(UserDO userDTO) {
        // 查询列表数据
        Page<UserDO> page = userService.selectPage(getPage(UserDO.class), null);
        List<UserDO>lists = page.getRecords();
        for (int i = 0 ; i < lists.size() ; i++){

            UserRoleDO userRoleDO =new UserRoleDO();
            userRoleDO.setUserId(lists.get(i).getId());
            userRoleDO = userRoleDao.selectOne(userRoleDO);
            if (userRoleDO!=null){
                RoleDO roleDO = roleService.selectById(userRoleDO.getRoleId());
                if (roleDO!=null){
                    lists.get(i).setRoleIdName(roleDO.getRoleName());
                    lists.get(i).setRoleId(roleDO.getId());
                }
            }
        }
        //page.setRecords(lists);
        return Result.ok(page);
    }

    
    @RequiresPermissions("sys:user:add")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.selectList(null);
        model.addAttribute("roles", roles);
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @GetMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        List<RoleDO> roles = roleService.findListStatusByUserId(id);
        model.addAttribute("roles", roles);
        return prefix + "/edit";
    }

    //@RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @ApiOperation("添加用户")
    @PostMapping("/save")
    @ResponseBody
    public Result<String> save(@RequestBody  UserDO user) {
        String username = user.getUsername();
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("username",username);
        UserDO u = userService.selectOne(wrapper);
        if (u!=null){
            Result result = new Result();
            result.setMsg("已存在该用户名！");
            result.setCode(100);
            return result ;
        }
        user.setStatus(1);
        Date data = new Date();
        user.setGmtCreate(data);
        userService.insert(user);
        UserRoleDO userRoleDO = new UserRoleDO();
        userRoleDO.setUserId(user.getId());
        userRoleDO.setRoleId(user.getRoleId());
        userRoleDao.insert(userRoleDO);
        return Result.ok();
    }

    //@RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @ApiOperation("更新用户")
    @PostMapping("/update")
    @ResponseBody
    public Result<String> update(@RequestBody  UserDO user) {
        if (user.getRoleId()!=null){
            userRoleDao.removeByUserId(user.getId());
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setUserId(user.getId());
            userRoleDO.setRoleId(user.getRoleId());
            userRoleDao.insert(userRoleDO);
        }
        //添加修改时间
        Date data = new Date();
        user.setGmtModified(data);
        userService.updateById(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    Result<String> remove(Long id) {
        userService.deleteById(id);
        return Result.ok();
    }

    //@RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @ApiOperation("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    public Result<String> batchRemove(@RequestBody List<Long> idList) {  //@RequestParam("ids[]")
        for (Long id : idList) {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id",id);
            boolean b = userService.delete(wrapper);
            System.out.println("b = " + b);
        }
        return Result.ok();
    }
    
    @PostMapping("/exist")
    @ResponseBody
    boolean exist(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exist(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result<String> resetPwd(UserVO userVO) {
        userService.resetPwd(userVO, getUser());
        return Result.ok();
    }

    //@RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(@RequestBody UserVO userVO) {
        int flag = userService.adminResetPwd(userVO);
        if(flag==-1){
            return Result.ok("原始密码输入错误");
        }
        return Result.ok();

    }
    
    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }
    
    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }
    
    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.selectById(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }
    
    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }

    @GetMapping("/unlock")
    @ResponseBody
    public Result<String> unlock(Long id){

        UserDO user = userService.selectById(id);
        user.setLocked(false);
        user.setLoginNum(0);
        userService.updateById(user);
        return Result.ok();
    }

}
